const { save, find, del, updateToken, update } = require("../model/positionsModel")
// 增加职位处理函数
const addCtr = async (req, res) => {
    //添加一个字段token_id
    // req.body.token_id = ?
    const arr = await find({ query: {} });//插入之前先查库 获取数组的长度
    const token_id = arr.length + 1
    //添加token_id到body
    req.body.token_id = token_id

    const result = await save(req.body)
    if (result) {
        res.send({ status: true, code: 1, msg: "保存成功" })
    } else {
        res.send({ status: false, code: 0, msg: "保存失败" })
    }
}
//查
const getlistCtr = async (req, res) => {
    let count = req.query.count || 3;
    let page = req.query.page || 1;
    let token_id = req.query.token_id
    //搜索功能  首先获取用户传递过来的query值
    let { wd } = req.query
    // find({companyName:/助教/})
    // find({token_id:2})
    let query;//find查询条件
    if (wd && token_id) {
        query = { token_id: token_id, companyName: new RegExp(wd) }
    } else if (token_id) {
        query = { token_id: token_id }
    } else if (wd) {
        query = { companyName: new RegExp(wd) }
    } else {
        query = {}
    }

    let info = {
        page: (page - 1) * count, //skip(0)跳过的数目
        count: count * 1,
        query: query
    }

    const result = await find(info);
    if (result) {
        res.send({ status: true, code: 1, data: result })
    } else {
        res.send({ status: false, code: 0, msg: "获取失败" })
    }
}
//删除
const delCtr = async (req, res) => {
    //获取前端传入的token_id
    let { token_id } = req.query;
    const result = await del(token_id)
    const updated = await updateToken(token_id)
    if (result.n && updated) {
        //删除成功之后更新 大于被删除的token_id的数据  它们的token_id自减1
        res.send({ status: true, code: 1, msg: "删除成功" })
    } else {
        res.send({ status: false, code: 0, msg: "删除失败" })
    }
}

//更新
const updateCtr = async (req, res) => {
    let { token_id } = req.body;
    //传递给model层更新的query参数
    let query = { token_id: token_id }
    const result = await update(query, req.body)
}

module.exports = {
    addCtr,
    getlistCtr,
    delCtr,
    updateCtr
}